import 'package:flutter/material.dart';

class TransactionHistoryScreen extends StatefulWidget {
  const TransactionHistoryScreen({super.key});

  @override
  State<TransactionHistoryScreen> createState() => _TransactionHistoryScreenState();
}

class _TransactionHistoryScreenState extends State<TransactionHistoryScreen> {
  String selectedFilter = '全部';
  final List<String> filters = ['全部', '购买', '出售', '转账', '收款'];
  
  // 模拟交易记录数据
  final List<Map<String, dynamic>> transactions = [
    {
      'id': 'TXN001',
      'type': '购买',
      'nftName': '苏绣·花鸟图',
      'amount': '¥2,800',
      'date': '2024-01-15 14:30',
      'status': '已完成',
      'counterparty': '王师傅工作室',
      'txHash': '0x1234...abcd',
      'gasUsed': '0.002 ETH',
    },
    {
      'id': 'TXN002',
      'type': '出售',
      'nftName': '青花瓷·梅兰竹菊',
      'amount': '¥5,200',
      'date': '2024-01-14 09:15',
      'status': '已完成',
      'counterparty': '收藏家李先生',
      'txHash': '0x5678...efgh',
      'gasUsed': '0.003 ETH',
    },
    {
      'id': 'TXN003',
      'type': '转账',
      'nftName': '剪纸·龙凤呈祥',
      'amount': '¥680',
      'date': '2024-01-13 16:45',
      'status': '处理中',
      'counterparty': '张艺人',
      'txHash': '0x9abc...ijkl',
      'gasUsed': '0.001 ETH',
    },
    {
      'id': 'TXN004',
      'type': '收款',
      'nftName': '木雕·观音像',
      'amount': '¥3,500',
      'date': '2024-01-12 11:20',
      'status': '已完成',
      'counterparty': '古玩收藏馆',
      'txHash': '0xdef0...mnop',
      'gasUsed': '0.002 ETH',
    },
    {
      'id': 'TXN005',
      'type': '购买',
      'nftName': '漆器·首饰盒',
      'amount': '¥1,200',
      'date': '2024-01-11 13:55',
      'status': '已完成',
      'counterparty': '传统工艺坊',
      'txHash': '0x1357...qrst',
      'gasUsed': '0.001 ETH',
    },
  ];

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: AppBar(
        title: const Text('交易记录'),
        backgroundColor: Colors.white,
        foregroundColor: const Color(0xFF333333),
        elevation: 0,
        leading: IconButton(
          icon: const Icon(Icons.arrow_back_ios, size: 16),
          onPressed: () {
            Navigator.pop(context);
          },
        ),
        actions: [
          IconButton(
            icon: const Icon(Icons.filter_list, size: 20),
            onPressed: () {
              _showFilterDialog();
            },
          ),
        ],
      ),
      body: Column(
        children: [
          // 统计信息卡片
          Container(
            margin: const EdgeInsets.all(20),
            padding: const EdgeInsets.all(20),
            decoration: BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.circular(16),
              boxShadow: const [
                BoxShadow(
                  color: Color(0x1A000000),
                  blurRadius: 10,
                  offset: Offset(0, 2),
                ),
              ],
            ),
            child: Row(
              children: [
                Expanded(
                  child: _buildStatItem('总交易', '${transactions.length}', Icons.swap_horiz),
                ),
                Container(
                  width: 1,
                  height: 40,
                  color: const Color(0xFFF0F2F5),
                ),
                Expanded(
                  child: _buildStatItem('本月', '3', Icons.calendar_today),
                ),
                Container(
                  width: 1,
                  height: 40,
                  color: const Color(0xFFF0F2F5),
                ),
                Expanded(
                  child: _buildStatItem('成功率', '95%', Icons.check_circle),
                ),
              ],
            ),
          ),
          
          // 筛选标签
          Container(
            height: 50,
            margin: const EdgeInsets.symmetric(horizontal: 20),
            child: ListView.builder(
              scrollDirection: Axis.horizontal,
              itemCount: filters.length,
              itemBuilder: (context, index) {
                final filter = filters[index];
                final isSelected = selectedFilter == filter;
                return GestureDetector(
                  onTap: () {
                    setState(() {
                      selectedFilter = filter;
                    });
                  },
                  child: Container(
                    margin: const EdgeInsets.only(right: 12),
                    padding: const EdgeInsets.symmetric(
                      horizontal: 16,
                      vertical: 8,
                    ),
                    decoration: BoxDecoration(
                      color: isSelected 
                          ? const Color(0xFF1890FF) 
                          : Colors.white,
                      borderRadius: BorderRadius.circular(20),
                      boxShadow: const [
                        BoxShadow(
                          color: Color(0x1A000000),
                          blurRadius: 8,
                          offset: Offset(0, 2),
                        ),
                      ],
                    ),
                    child: Center(
                      child: Text(
                        filter,
                        style: TextStyle(
                          color: isSelected 
                              ? Colors.white 
                              : const Color(0xFF333333),
                          fontSize: 14,
                          fontWeight: isSelected 
                              ? FontWeight.bold 
                              : FontWeight.normal,
                        ),
                      ),
                    ),
                  ),
                );
              },
            ),
          ),
          
          const SizedBox(height: 20),
          
          // 交易记录列表
          Expanded(
            child: ListView.builder(
              padding: const EdgeInsets.symmetric(horizontal: 20),
              itemCount: _getFilteredTransactions().length,
              itemBuilder: (context, index) {
                final transaction = _getFilteredTransactions()[index];
                return _buildTransactionItem(transaction);
              },
            ),
          ),
        ],
      ),
    );
  }
  
  Widget _buildStatItem(String label, String value, IconData icon) {
    return Column(
      children: [
        Icon(
          icon,
          color: const Color(0xFF1890FF),
          size: 20,
        ),
        const SizedBox(height: 8),
        Text(
          value,
          style: const TextStyle(
            fontSize: 18,
            fontWeight: FontWeight.bold,
            color: Color(0xFF333333),
          ),
        ),
        const SizedBox(height: 4),
        Text(
          label,
          style: const TextStyle(
            fontSize: 12,
            color: Color(0xFF666666),
          ),
        ),
      ],
    );
  }
  
  List<Map<String, dynamic>> _getFilteredTransactions() {
    if (selectedFilter == '全部') {
      return transactions;
    }
    return transactions.where((tx) => tx['type'] == selectedFilter).toList();
  }

  Widget _buildTransactionItem(Map<String, dynamic> transaction) {
    Color statusColor;
    Color typeColor;
    IconData typeIcon;
    
    // 根据状态设置颜色
    switch (transaction['status']) {
      case '已完成':
        statusColor = const Color(0xFF52C41A);
        break;
      case '处理中':
        statusColor = const Color(0xFFFAAD14);
        break;
      case '失败':
        statusColor = const Color(0xFFF5222D);
        break;
      default:
        statusColor = const Color(0xFF666666);
    }
    
    // 根据交易类型设置颜色和图标
    switch (transaction['type']) {
      case '购买':
        typeColor = const Color(0xFF1890FF);
        typeIcon = Icons.shopping_cart;
        break;
      case '出售':
        typeColor = const Color(0xFF52C41A);
        typeIcon = Icons.sell;
        break;
      case '转账':
        typeColor = const Color(0xFFFAAD14);
        typeIcon = Icons.send;
        break;
      case '收款':
        typeColor = const Color(0xFF722ED1);
        typeIcon = Icons.account_balance_wallet;
        break;
      default:
        typeColor = const Color(0xFF666666);
        typeIcon = Icons.swap_horiz;
    }
    
    return Container(
      margin: const EdgeInsets.only(bottom: 16),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(12),
        boxShadow: const [
          BoxShadow(
            color: Color(0x1A000000),
            blurRadius: 10,
            offset: Offset(0, 2),
          ),
        ],
      ),
      child: InkWell(
        onTap: () {
          _showTransactionDetail(transaction);
        },
        borderRadius: BorderRadius.circular(12),
        child: Padding(
          padding: const EdgeInsets.all(16),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              // 顶部信息行
              Row(
                children: [
                  // 交易类型图标
                  Container(
                    width: 40,
                    height: 40,
                    decoration: BoxDecoration(
                      color: typeColor.withOpacity(0.1),
                      borderRadius: BorderRadius.circular(20),
                    ),
                    child: Icon(
                      typeIcon,
                      color: typeColor,
                      size: 20,
                    ),
                  ),
                  const SizedBox(width: 12),
                  
                  // 交易信息
                  Expanded(
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: [
                            Text(
                              transaction['type'],
                              style: TextStyle(
                                fontSize: 16,
                                fontWeight: FontWeight.bold,
                                color: typeColor,
                              ),
                            ),
                            Text(
                              transaction['amount'],
                              style: const TextStyle(
                                fontSize: 16,
                                fontWeight: FontWeight.bold,
                                color: Color(0xFF333333),
                              ),
                            ),
                          ],
                        ),
                        const SizedBox(height: 4),
                        Text(
                          transaction['nftName'],
                          style: const TextStyle(
                            fontSize: 14,
                            color: Color(0xFF333333),
                          ),
                        ),
                      ],
                    ),
                  ),
                ],
              ),
              
              const SizedBox(height: 12),
              
              // 分割线
              Container(
                height: 1,
                color: const Color(0xFFF0F2F5),
              ),
              
              const SizedBox(height: 12),
              
              // 底部详细信息
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(
                        '交易对象',
                        style: const TextStyle(
                          fontSize: 12,
                          color: Color(0xFF666666),
                        ),
                      ),
                      const SizedBox(height: 2),
                      Text(
                        transaction['counterparty'],
                        style: const TextStyle(
                          fontSize: 14,
                          color: Color(0xFF333333),
                        ),
                      ),
                    ],
                  ),
                  Column(
                    crossAxisAlignment: CrossAxisAlignment.end,
                    children: [
                      Container(
                        padding: const EdgeInsets.symmetric(
                          horizontal: 8,
                          vertical: 4,
                        ),
                        decoration: BoxDecoration(
                          color: statusColor.withOpacity(0.1),
                          borderRadius: BorderRadius.circular(12),
                        ),
                        child: Text(
                          transaction['status'],
                          style: TextStyle(
                            fontSize: 12,
                            fontWeight: FontWeight.bold,
                            color: statusColor,
                          ),
                        ),
                      ),
                      const SizedBox(height: 4),
                      Text(
                        transaction['date'],
                        style: const TextStyle(
                          fontSize: 12,
                          color: Color(0xFF666666),
                        ),
                      ),
                    ],
                  ),
                ],
              ),
            ],
          ),
        ),
      ),
    );
  }
  
  void _showFilterDialog() {
    showModalBottomSheet(
      context: context,
      backgroundColor: Colors.transparent,
      builder: (context) => Container(
        decoration: const BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.only(
            topLeft: Radius.circular(20),
            topRight: Radius.circular(20),
          ),
        ),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            Container(
              margin: const EdgeInsets.only(top: 8),
              width: 40,
              height: 4,
              decoration: BoxDecoration(
                color: const Color(0xFFE0E0E0),
                borderRadius: BorderRadius.circular(2),
              ),
            ),
            const Padding(
              padding: EdgeInsets.all(20),
              child: Text(
                '筛选交易类型',
                style: TextStyle(
                  fontSize: 18,
                  fontWeight: FontWeight.bold,
                  color: Color(0xFF333333),
                ),
              ),
            ),
            ...filters.map((filter) => ListTile(
              title: Text(filter),
              trailing: selectedFilter == filter 
                  ? const Icon(Icons.check, color: Color(0xFF1890FF))
                  : null,
              onTap: () {
                setState(() {
                  selectedFilter = filter;
                });
                Navigator.pop(context);
              },
            )),
            const SizedBox(height: 20),
          ],
        ),
      ),
    );
  }
  
  void _showTransactionDetail(Map<String, dynamic> transaction) {
    showModalBottomSheet(
      context: context,
      backgroundColor: Colors.transparent,
      isScrollControlled: true,
      builder: (context) => Container(
        height: MediaQuery.of(context).size.height * 0.7,
        decoration: const BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.only(
            topLeft: Radius.circular(20),
            topRight: Radius.circular(20),
          ),
        ),
        child: Column(
          children: [
            Container(
              margin: const EdgeInsets.only(top: 8),
              width: 40,
              height: 4,
              decoration: BoxDecoration(
                color: const Color(0xFFE0E0E0),
                borderRadius: BorderRadius.circular(2),
              ),
            ),
            Padding(
              padding: const EdgeInsets.all(20),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  const Text(
                    '交易详情',
                    style: TextStyle(
                      fontSize: 18,
                      fontWeight: FontWeight.bold,
                      color: Color(0xFF333333),
                    ),
                  ),
                  IconButton(
                    icon: const Icon(Icons.close),
                    onPressed: () => Navigator.pop(context),
                  ),
                ],
              ),
            ),
            Expanded(
              child: SingleChildScrollView(
                padding: const EdgeInsets.symmetric(horizontal: 20),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    _buildDetailItem('交易ID', transaction['id']),
                    _buildDetailItem('交易类型', transaction['type']),
                    _buildDetailItem('NFT名称', transaction['nftName']),
                    _buildDetailItem('交易金额', transaction['amount']),
                    _buildDetailItem('交易对象', transaction['counterparty']),
                    _buildDetailItem('交易时间', transaction['date']),
                    _buildDetailItem('交易状态', transaction['status']),
                    _buildDetailItem('交易哈希', transaction['txHash']),
                    _buildDetailItem('Gas费用', transaction['gasUsed']),
                    const SizedBox(height: 20),
                    
                    // 操作按钮
                    Row(
                      children: [
                        Expanded(
                          child: OutlinedButton(
                            onPressed: () {
                              // 复制交易哈希
                            },
                            style: OutlinedButton.styleFrom(
                              foregroundColor: const Color(0xFF1890FF),
                              side: const BorderSide(
                                color: Color(0xFF1890FF),
                                width: 1,
                              ),
                              shape: RoundedRectangleBorder(
                                borderRadius: BorderRadius.circular(8),
                              ),
                              padding: const EdgeInsets.symmetric(vertical: 12),
                            ),
                            child: const Text(
                              '复制哈希',
                              style: TextStyle(
                                fontSize: 14,
                                fontWeight: FontWeight.bold,
                              ),
                            ),
                          ),
                        ),
                        const SizedBox(width: 12),
                        Expanded(
                          child: ElevatedButton(
                            onPressed: () {
                              // 查看区块链浏览器
                            },
                            style: ElevatedButton.styleFrom(
                              backgroundColor: const Color(0xFF1890FF),
                              foregroundColor: Colors.white,
                              elevation: 0,
                              shape: RoundedRectangleBorder(
                                borderRadius: BorderRadius.circular(8),
                              ),
                              padding: const EdgeInsets.symmetric(vertical: 12),
                            ),
                            child: const Text(
                              '区块浏览器',
                              style: TextStyle(
                                fontSize: 14,
                                fontWeight: FontWeight.bold,
                              ),
                            ),
                          ),
                        ),
                      ],
                    ),
                    const SizedBox(height: 20),
                  ],
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
  
  Widget _buildDetailItem(String label, String value) {
    return Container(
      margin: const EdgeInsets.only(bottom: 16),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          SizedBox(
            width: 80,
            child: Text(
              label,
              style: const TextStyle(
                fontSize: 14,
                color: Color(0xFF666666),
              ),
            ),
          ),
          const SizedBox(width: 12),
          Expanded(
            child: Text(
              value,
              style: const TextStyle(
                fontSize: 14,
                color: Color(0xFF333333),
                fontWeight: FontWeight.w500,
              ),
            ),
          ),
        ],
      ),
    );
  }
}